import java.awt.event.HierarchyBoundsAdapter;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Solution solution=new Solution();
        Scanner scanner=new Scanner(System.in);
        int n=scanner.nextInt();
        int[] array=new int[6];
        for(int i=0;i<n;i++){
            array[i]=scanner.nextInt();
        }
        System.out.println(solution.trap(array));
    }
    public static void main1(String[] args) {
       Solution1 solution1=new Solution1();
        Scanner scanner=new Scanner(System.in);
        int n=scanner.nextInt();
        System.out.println(solution1.climbStairs(n));
    }
}

class Solution {
    public int trap(int[] height) {
        int res=0;
        int n=height.length;
        int[]dp=new int[n];
        int l=0;
        dp[n-1]= height[n-1];
        for (int i = n-2; i >=0 ; i--) {
            dp[i]=Math.max(height[i],dp[i+1]);
        }
        for(int i=1;i<n-1;i++){
            l=Math.max(l,height[i-1]);
            int min=Math.min(l,dp[i]);
            if(min>height[i]){
                res+=min-height[i];
            }
        }
        return res;
    }
}


class Solution1 {
    public int climbStairs(int n) {
        int[] dp=new int[50];
        dp[1]=1;
        dp[2]=2;
        for(int i=3;i<=n;i++){
            dp[i]=dp[i-1]+dp[i-2];
        }
        return dp[n];
    }
}